<template>
  <div class="rider-detail-container">
    <div class="page-header">
      <el-page-header @back="goBack" :title="`骑手详情 #${riderId}`" />
    </div>

    <div class="rider-content" v-loading="loading">
      <!-- 骑手基本信息 -->
      <el-row :gutter="20" class="main-info-row">
        <el-col :span="8">
          <el-card class="rider-info-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>骑手信息</h3>
                <el-button type="primary" size="small" @click="handleEdit" :icon="Edit">编辑</el-button>
              </div>
            </template>
            <div class="rider-profile">
              <div class="rider-avatar">
                <el-avatar :size="100" :icon="UserFilled" />
              </div>
              <div class="rider-basic-info">
                <h2>{{ riderInfo.name }}</h2>
                <el-tag :type="getRiderStatusType(riderInfo.status)" effect="dark" class="status-tag">
                  {{ getRiderStatusText(riderInfo.status) }}
                </el-tag>
              </div>
            </div>
            <el-divider />
            <div class="info-list">
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span class="info-value">{{ riderInfo.phone }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">交通工具：</span>
                <span class="info-value">{{ getVehicleTypeText(riderInfo.vehicleType) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">当前订单数：</span>
                <span class="info-value">{{ riderInfo.currentOrderCount || 0 }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">加入时间：</span>
                <span class="info-value">{{ riderInfo.joinDate || '未知' }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="16">
          <el-row :gutter="20" class="stats-row">
            <el-col :span="8" v-for="(stat, index) in performanceStats" :key="index">
              <el-card class="stat-card" shadow="hover">
                <div class="stat-content">
                  <div class="stat-icon" :class="stat.colorClass">
                    <el-icon><component :is="stat.icon" /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ stat.value }}</div>
                    <div class="stat-label">{{ stat.label }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 评分卡片 -->
          <el-card class="rating-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>配送评分</h3>
              </div>
            </template>
            <div class="rating-content">
              <div class="rating-overall">
                <div class="rating-score">{{ (riderInfo.avgRating || 4.8).toFixed(1) }}</div>
                <div class="rating-stars">
                  <el-rate
                    v-model="riderInfo.avgRating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template=""
                  />
                </div>
                <div class="rating-count">共 {{ riderInfo.ratingCount || 128 }} 次评分</div>
              </div>
              <div class="rating-breakdown">
                <div class="rating-item" v-for="(item, index) in ratingBreakdown" :key="index">
                  <span class="rating-label">{{ item.label }}</span>
                  <el-progress 
                    :percentage="item.percentage" 
                    :color="item.color" 
                    :stroke-width="8" 
                    :show-text="false"
                  />
                  <span class="rating-percent">{{ item.percentage }}%</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 配送历史 -->
      <el-card class="delivery-history-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>配送历史</h3>
            <div class="header-actions">
              <el-radio-group v-model="timeRange" size="small">
                <el-radio-button label="today">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="all">全部</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>

        <el-table :data="deliveryHistory" style="width: 100%" border stripe>
          <el-table-column prop="orderNo" label="订单号" width="200" align="center"/>
          <el-table-column prop="storeAddress" label="取货地址" min-width="150" align="center"/>
          <el-table-column prop="customerAddress" label="送货地址" min-width="150" align="center"/>
          <el-table-column prop="distance" label="配送距离" width="100" align="center">
            <template #default="scope">
              {{ scope.row.distance }} 公里
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="180" align="center"/>
          <el-table-column prop="endTime" label="完成时间" width="180" align="center">
            <template #default="scope">
              {{ scope.row.endTime ? scope.row.endTime : '配送中~~~' }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="配送时长" width="100" align="center">
            <template #default="scope">
              {{ scope.row.duration ? scope.row.duration  + '分钟': '配送中~~~' }} 
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getDeliveryStatusType(scope.row.deliveryStatus)">
                {{ scope.row.statusText }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="rating" label="评分" width="120">
            <template #default="scope">
              <el-rate v-model="scope.row.rating" disabled text-color="#ff9900" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewOrderDetail(scope.row.orderId)" :icon="View">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="historyTotal"
            :page-size="historyPageSize"
            :current-page="historyCurrentPage"
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleHistorySizeChange"
            @current-change="handleHistoryCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 编辑骑手对话框 -->
    <el-dialog
      title="编辑骑手信息"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="editForm" :rules="riderRules" ref="editFormRef" label-width="100px">
        <el-form-item label="骑手姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入骑手姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="交通工具" prop="vehicleType">
          <el-select v-model="editForm.vehicleType" placeholder="请选择交通工具">
            <el-option label="电动车" value="electric_bike" />
            <el-option label="摩托车" value="motorcycle" />
            <el-option label="自行车" value="bicycle" />
            <el-option label="步行" value="walk" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="离线" :value="0" />
            <el-option label="空闲" :value="1" />
            <el-option label="忙碌" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getRiderById, updateRider, getRiderStats, getRiderDeliveryHistory } from '@/api/riders';
import {
  UserFilled,
  Edit,
  View,
  Bicycle,
  Timer,
  Star,
  Medal,
  TrendCharts,
  Money
} from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const riderId = ref(route.params.id);
const loading = ref(true);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const timeRange = ref('week');

// 骑手信息
const riderInfo = ref({
  id: riderId.value,
  name: '张三',
  phone: '13800138000',
  vehicleType: 'electric_bike',
  status: 1,
  currentOrderCount: 3,
  joinDate: '2023-01-15',
  avgRating: 4.8
});

// 编辑表单
const editFormRef = ref(null);
const editForm = reactive({
  id: null,
  name: '',
  phone: '',
  vehicleType: '',
  status: 0
});

const riderRules = {
  name: [
    { required: true, message: '请输入骑手姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  vehicleType: [
    { required: true, message: '请选择交通工具', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 绩效统计数据
const performanceStats = ref([
  { 
    label: '今日订单', 
    value: '15单', 
    icon: 'Bicycle',
    colorClass: 'color-primary'
  },
  { 
    label: '平均配送时间', 
    value: '25分钟', 
    icon: 'Timer',
    colorClass: 'color-success'
  },
  { 
    label: '准时率', 
    value: '98%', 
    icon: 'Medal',
    colorClass: 'color-warning'
  },
  { 
    label: '本月订单', 
    value: '324单', 
    icon: 'TrendCharts',
    colorClass: 'color-danger'
  },
  { 
    label: '本月收入', 
    value: '¥3,240', 
    icon: 'Money',
    colorClass: 'color-info'
  },
  { 
    label: '好评率', 
    value: '96%', 
    icon: 'Star',
    colorClass: 'color-primary'
  }
]);

// 评分分布
const ratingBreakdown = ref([
  { label: '5星', percentage: 85, color: '#67c23a' },
  { label: '4星', percentage: 10, color: '#409eff' },
  { label: '3星', percentage: 3, color: '#e6a23c' },
  { label: '2星', percentage: 1, color: '#f56c6c' },
  { label: '1星', percentage: 1, color: '#909399' }
]);

// 配送历史
const deliveryHistory = ref([]);
const historyTotal = ref(0);
const historyCurrentPage = ref(1);
const historyPageSize = ref(10);

// 获取骑手详情
const fetchRiderDetail = async () => {
  loading.value = true;
  try {
    const res = await getRiderById(riderId.value);
    if (res.code === 200) {
      riderInfo.value = res.data;
      
      // 更新编辑表单
      editForm.id = riderInfo.value.id;
      editForm.name = riderInfo.value.name;
      editForm.phone = riderInfo.value.phone;
      editForm.vehicleType = riderInfo.value.vehicleType;
      editForm.status = riderInfo.value.status;
      
      // 获取骑手统计数据
      fetchRiderStats();
    } else {
      ElMessage.error(res.msg || '获取骑手详情失败');
    }
  } catch (error) {
    console.error('获取骑手详情失败:', error);
    ElMessage.error('获取骑手详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取骑手统计数据
const fetchRiderStats = async () => {
  try {
    const res = await getRiderStats(riderId.value);
    if (res.code === 200) {
      const stats = res.data;
      
      // 更新统计卡片数据
      performanceStats.value = [
        { 
          label: '今日订单', 
          value: `${stats.todayOrderCount || 0}单`, 
          icon: 'Bicycle',
          colorClass: 'color-primary'
        },
        { 
          label: '平均配送时间', 
          value: `${stats.avgDeliveryTime || 0}分钟`, 
          icon: 'Timer',
          colorClass: 'color-success'
        },
        { 
          label: '准时率', 
          value: `${stats.onTimeRate ? stats.onTimeRate.toFixed(0) : 0}%`, 
          icon: 'Medal',
          colorClass: 'color-warning'
        },
        { 
          label: '本月订单', 
          value: `${stats.monthOrderCount || 0}单`, 
          icon: 'TrendCharts',
          colorClass: 'color-danger'
        },
        { 
          label: '本周订单', 
          value: `${stats.weekOrderCount || 0}单`, 
          icon: 'TrendCharts',
          colorClass: 'color-info'
        },
        { 
          label: '总完成订单', 
          value: `${stats.totalOrderCount || 0}单`, 
          icon: 'Star',
          colorClass: 'color-primary'
        }
      ];
    }
  } catch (error) {
    console.error('获取骑手统计数据失败:', error);
  }
};

// 获取配送历史
const fetchDeliveryHistory = async () => {
  try {
    const params = {
      page: historyCurrentPage.value,
      pageSize: historyPageSize.value,
      timeRange: timeRange.value
    };
    
    const res = await getRiderDeliveryHistory(riderId.value, params);
    if (res.code === 200) {
      deliveryHistory.value = res.data.items;
      historyTotal.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取配送历史失败');
    }
  } catch (error) {
    console.error('获取配送历史失败:', error);
    ElMessage.error('获取配送历史失败');
  }
};

// 监听时间范围变化
watch(timeRange, () => {
  historyCurrentPage.value = 1;
  fetchDeliveryHistory();
});

// 返回上一页
const goBack = () => {
  router.push('/home/riders');
};

// 编辑骑手信息
const handleEdit = () => {
  editForm.id = riderInfo.value.id;
  editForm.name = riderInfo.value.name;
  editForm.phone = riderInfo.value.phone;
  editForm.vehicleType = riderInfo.value.vehicleType;
  editForm.status = riderInfo.value.status;
  dialogVisible.value = true;
};

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return;
  
  await editFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      const res = await updateRider(editForm);
      if (res.code === 200) {
        ElMessage.success('更新成功');
        fetchRiderDetail();
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新失败:', error);
      ElMessage.error('更新失败');
    } finally {
      submitLoading.value = false;
    }
  });
};

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/home/orders/detail/${orderId}`);
};

// 分页
const handleHistorySizeChange = (size) => {
  historyPageSize.value = size;
  fetchDeliveryHistory();
};

const handleHistoryCurrentChange = (page) => {
  historyCurrentPage.value = page;
  fetchDeliveryHistory();
};

// 获取骑手状态文本
const getRiderStatusText = (status) => {
  const statusMap = {
    0: '离线',
    1: '空闲',
    2: '忙碌'
  };
  return statusMap[status] || '未知';
};

// 获取骑手状态类型
const getRiderStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'success',
    2: 'warning'
  };
  return statusMap[status] || 'info';
};

// 获取交通工具文本
const getVehicleTypeText = (vehicleType) => {
  const vehicleTypeMap = {
    'electric_bike': '电动车',
    'motorcycle': '摩托车',
    'bicycle': '自行车',
    'walk': '步行'
  };
  return vehicleTypeMap[vehicleType] || vehicleType;
};

// 获取配送状态文本
const getDeliveryStatusText = (status) => {
  const statusMap = {
    0: '配送中',
    1: '已完成',
    2: '已取消'
  };
  return statusMap[status] || '未知';
};

// 获取配送状态类型
const getDeliveryStatusType = (status) => {
  const statusMap = {
    0: 'primary',
    1: 'success',
    2: 'danger'
  };
  return statusMap[status] || 'info';
};

onMounted(() => {
  fetchRiderDetail();
  fetchDeliveryHistory();
});
</script>

<style scoped>
.rider-detail-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.rider-content {
  margin-top: 20px;
  height: 100%;
}

/* Main info row should have a fixed height */
.main-info-row {
  min-height: 600px;
}

/* 骑手信息卡片样式 */
.rider-info-card {
  margin-bottom: 20px;
  height: calc(100% - 20px); /* Make it take full height minus margin */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.rider-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.rider-avatar {
  margin-bottom: 15px;
}

.rider-basic-info {
  text-align: center;
}

.rider-basic-info h2 {
  margin: 0 0 10px;
  font-size: 20px;
}

.status-tag {
  margin-top: 5px;
}

.info-list {
  margin-top: 10px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.info-label {
  font-weight: bold;
  min-width: 100px;
}

/* 统计卡片样式 */
.stat-card {
  margin-bottom: 20px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  text-align: center;
}

/* Center all stat cards in the row */
.stats-row {
  display: flex;
  justify-content: center;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  text-align: center;
}

.stat-icon .el-icon {
  font-size: 24px;
  color: white;
}

.color-primary {
  background-color: #409eff;
}

.color-success {
  background-color: #67c23a;
}

.color-warning {
  background-color: #e6a23c;
}

.color-danger {
  background-color: #f56c6c;
}

.color-info {
  background-color: #909399;
}

.stat-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  text-align: center;
}

/* 评分卡片样式 */
.rating-card {
  margin-bottom: 20px;
  height: calc(100% - 300px); /* Make it match height with rider info card, accounting for stat cards */
}

.rating-content {
  display: flex;
  gap: 30px;
}

.rating-overall {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #ebeef5;
  padding-right: 30px;
}

.rating-score {
  font-size: 48px;
  font-weight: bold;
  color: #ff9900;
  margin-bottom: 10px;
}

.rating-stars {
  margin-bottom: 10px;
}

.rating-count {
  font-size: 14px;
  color: #909399;
}

.rating-breakdown {
  flex: 2;
  padding-left: 20px;
}

.rating-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.rating-label {
  width: 40px;
  margin-right: 10px;
}

.rating-percent {
  width: 50px;
  text-align: right;
  margin-left: 10px;
}

.el-progress {
  flex: 1;
}

/* 配送历史卡片样式 */
.delivery-history-card {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 